<template>
  <div class="app-container">
    <!-- 表格-条件筛区域  -->
    <div class="filter-container">
      <el-input placeholder="请输入折扣券名称" v-model="searchParam.SEARCH_LIKE_coupon_name" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"> 搜索 </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleCreate"> 新增 </el-button>
    </div>

    <!-- 表格-内容区域 -->
    <el-table v-loading="listLoading" :key="tableKey" :data="tableList" border fit highlight-current-row style="width: 100%;">
      <el-table-column v-for="column in columns" :key="column.prop"
                       :prop="column.prop"
                       :label="column.label"
                       :width="column.width"
                       :align="column.align?column.align:'center'"
                       :min-width="column.minWidth"
                       :sortable="column.sortable"
                       :fixed="column.fixed"
                       :type="column.type" :formatter="column.formatter">
        <template slot-scope="scope">
          <!-- 行内显示图片 -->
          <img v-if="column.imgFlag==true" :src=" scope.row[column.prop].indexOf('http://') >-1 ?  scope.row[column.prop] : ( CMBASE.baseFileContext + scope.row[column.prop] ) " width="60" height="60" class="img"/>
          <!-- 行内显示开关按钮 -->
          <el-switch v-else-if="column.switchFlag==true" v-model="scope.row[column.prop]" :active-value="1" :inactive-value="0"  disabled />
          <!-- 行内显示tag标签 -->
          <span  v-else-if="column.tagFlag==true">
                        <span v-for="item in column.tagFormatter" :key="item.value" >
                            <el-tag v-if="item.value==scope.row[column.prop]"   :type="item.type">{{item.text}}</el-tag>
                        </span>
                    </span>
          <!-- 行内格式自定义 -->
          <span v-else-if="column.formatter"> {{column.formatter(scope.row)}}</span>
          <!--默认显示文本-->
          <span v-else>{{scope.row[column.prop]}}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="240" class-name="small-padding">
        <template slot-scope="scope">
          <el-button type="text"  icon="el-icon-edit" class="el-button--primary"  @click="handleUpdate(scope.row)"> 编辑 </el-button>
          <el-button type="text" icon="el-icon-edit" class="el-button--primary" @click="handleInfo(scope.row)" > 展开 </el-button>
          <el-button type="text"  icon="el-icon-delete"   class="el-button--danger"  @click="handleDelete(scope.row)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格-页脚区域 -->
    <pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="pageRequest.pageNum" :limit.sync="pageRequest.pageSize" @pagination="getList"/>

    <!--新增编辑界面-->
    <el-dialog :title="operation?'新增':'编辑'" width="45%" top="5vh" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form :model="dataForm" label-width="140px" :rules="dataFormRules" ref="dataForm" style="width: 80%">

        <el-form-item label="折扣券券名称" prop="couponName">
          <el-input v-model="dataForm.couponName" auto-complete="off" placeholder="请输入优惠券名称"/>
        </el-form-item>
        <el-form-item label="折扣券类型" prop="type">
          <el-select v-model="dataForm.type" placeholder="请选择下拉数据">
            <el-option label="不限制" :value="0"></el-option>
            <el-option label="课程" :value="1"></el-option>
            <el-option label="考试" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="dataForm.type === 1" label="限制课程" prop="useLimit">
          <el-select v-model="dataForm.useLimit" multiple placeholder="请选择下拉数据">
            <el-option v-for="item in questionOptions" :label="item.label" :key="item.value" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="dataForm.type === 2" label="限制考试" prop="useLimit">
          <el-select v-model="dataForm.useLimit" multiple placeholder="请选择下拉数据">
            <el-option v-for="item in examOptions" :label="item.label" :key="item.value" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item  label="使用限制-用户" prop="userLimit">
          <el-select v-model="dataForm.userLimit" filterable clearable multiple placeholder="请选择下拉数据">
            <el-option v-for="item in userOptions " :key="item.value" :value="item.value" :label="item.label" ></el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="编号" prop="couponNum">-->
<!--          <el-input disabled v-model="dataForm.couponNum" auto-complete="off" placeholder="请输入编号"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="激活密钥" prop="activeSecret">-->
<!--          <el-input disabled v-model="dataForm.activeSecret" auto-complete="off" placeholder="请输入激活密钥"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="激活码" prop="activeCode">-->
<!--          <el-input disabled v-model="dataForm.activeCode" auto-complete="off" placeholder="请输入激活码"/>-->
<!--        </el-form-item>-->
        <el-form-item label="有效天数" prop="effectiveDay">
          <el-input-number v-model="dataForm.effectiveDay"   :min="1" :max="1000" label="有效天数"></el-input-number>
        </el-form-item>
        <el-form-item label="折扣比率" prop="discountRatio">
          <el-input-number v-model="dataForm.discountRatio"   :min="0" :max="1" label="折扣比率"></el-input-number> <span style="color: red">单位:(小数)</span>
        </el-form-item>
        <el-form-item label="发放张数" prop="grantNum">
          <el-input-number v-model="dataForm.grantNum" :min="0" :max="1000" :step="1" step-strictly label="发放张数" ></el-input-number>
        </el-form-item>
        <el-form-item label="每人限领" prop="limitCount">
          <el-input-number v-model="dataForm.limitCount" :min="1" :max="1000" :step="1" step-strictly label="每人限领张数" ></el-input-number>
        </el-form-item>
        <el-form-item label="是否展示" prop="isShow">
          <el-radio-group v-model="dataForm.isShow">
            <el-radio-button :label=0 >否</el-radio-button>
            <el-radio-button :label=1 >是</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="closeDialog()">取消</el-button>
        <el-button size="mini" @click.native="saveFormData()" :loading="editLoading" type="primary">提交 </el-button>
      </div>
    </el-dialog>

    <el-dialog
        title="卡密列表"
        :visible.sync="itemDialog"
        width="65%"
    >
      <coupon-item v-if="itemDialog" :pid="this.pid"></coupon-item>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="itemDialog = false">取消</el-button>
      </div>

    </el-dialog>

  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import {addSCouponsItem, getCourseList, getExamList, getUserList} from "@/api/modules/examApi"; // 分页栏信息
import CouponItem from "./couponItem.vue";
export default {
  name: 'coupon',
  components: {
    Pagination,
    CouponItem,
  },
  directives: {   },
  filters: { },
  data() {
    return {
      tableKey: 0,
      tableList: [],//表格数据源
      tableTotal: 0,//表格总条数数据
      listLoading: true,
      pageRequest: { pageNum: 1, pageSize: 10, },
      searchParam:{},
      orderParam: { create_time:false },
      dialogFormVisible: false,//默认不显示弹出框
      operation: true, // true:新增, false:编辑
      editLoading: false,//保存表单时loading框
      itemDialog: false,//保存表单时loading框
      columns: [
        // {prop: 'couponNum',  label: '编号',  sortable:false  },
        {prop: 'couponName',  label: '优惠券名称',  sortable:false  },
        {prop: 'type',  label: '优惠券类型',  sortable:false, tagFlag: true,
          tagFormatter: [
            {text: '考试', value: 2, type: 'danger'},
            {text: '课程', value: 1, type: 'warning'},
            {text: '通用', value: 0, type: 'success'},
          ]
        },
        // {prop: 'activeCode',  label: '激活码',  sortable:false ,width: 260 },
        // {prop: 'activeSecret',  label: '激活密钥',  sortable:false  },
        {prop: 'effectiveDay',  label: '有效天数',  sortable:false  },
        {prop: 'discountRatio',  label: '折扣比率',  sortable:false  },
        {prop: 'grantNum' ,label: '发放张数' , sortable:false },
        {prop: 'getNumber' ,label: '领取张数' , sortable:false },
        {prop: 'useNumber' ,label: '使用张数' , sortable:false },
        {prop: 'limitCount' ,label: '限制领取张数' , sortable:false, width:130 },
        {prop: 'isShow' ,label: '展示' , sortable:false, width:130, switchFlag:true },
        {prop: 'createTime',  label: '创建时间',  sortable:false  },
      ],
      fileList: [],
      // 新增编辑界面数据
      dataForm: {},
      //表单检验规则
      dataFormRules: {
        effectiveDay: [ { required: true, message: '请输入有效天数', trigger: 'blur' } ],
        discountRatio: [ { required: true, message: '请输入折扣比率', trigger: 'blur' } ],
        couponName: [ { required: true, message: '请输入优惠券名称', trigger: 'blur' } ],
        type: [ { required: true, message: '请输入优惠券类型', trigger: 'blur' } ],
        isShow: [ { required: true, message: '请设置是否展示', trigger: 'blur' } ],
      },
      userOptions:[],
      examOptions:[],
      questionOptions:[],
      pid:'',
    }
  },
  created() {
    this.getList();
    this.heandleUserOptions();
    this.heandleQuestionOptions();
    this.heandleExamOptions();
  },
  methods: {
    //获取表格数据
    getList() {
      this.listLoading = true
      //【API请求】----获取表格列表数据
      this.pageRequest.orderParam  = this.orderParam
      this.$api.getSCouponsList(this.pageRequest).then(response => {
        this.tableList = response.data.content
        this.tableTotal = response.data.total
        this.listLoading = false;
      }).catch((res) => {
        this.$message({  message: '列表获取失败', type: 'error' })
      })
    },
    //表格数据筛选
    handleFilter() {
        this.pageRequest = {
            pageNum: 1,
            pageSize: 10,
        }
      this.pageRequest.searchParam = this.searchParam
      this.getList()
    },
    //【按钮点击】--- 弹出新增表单
    handleCreate() {
      this.operation = true;
      this.initDataForm();
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false;
      })
    },
    //【按钮点击】--- 弹出编辑表单
    handleUpdate(row) {
      this.operation = false;
      this.dataForm = Object.assign({}, row)
      if(this.dataForm.useLimit){
        this.dataForm.useLimit = this.dataForm.useLimit.split(",")
      }
      if (this.dataForm.userLimit){
        this.dataForm.userLimit = this.dataForm.userLimit.split(",")
      }
      //显示编辑菜单
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false;
      })
    },
    //保存表单数据
     saveFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.editLoading = true;
        if (this.dataForm.useLimit){
          this.dataForm.useLimit = this.dataForm.useLimit.join(",")
        }
        if (this.dataForm.userLimit){
          this.dataForm.userLimit = this.dataForm.userLimit.join(",");
        }else{
          this.dataForm.userLimit =''
        }
        if (this.dataForm.type===0){
          this.dataForm.useLimit=''
        }
        //【API请求】----保存数据
          this.$api.saveSCoupons(this.dataForm).then( () => {
            this.editLoading = false;//关闭loading框
            this.dialogFormVisible = false;//关闭表单页面
            this.initDataForm();//重置表单数据
            this.getList();//重新获取表格数据
            this.$notify({title: '成功', message: '保存成功', type: 'success', duration: 2000})
          })

      })
    },


    //【按钮点击】---删除行
    handleDelete(row) {
      this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
        //【API请求】---- 删除数据
        this.$api.deleteSCoupons({ids:row.id}).then(() => {
          this.$message({  message: '操作成功', type: 'success' })
            this.pageRequest.pageNum = 1
          this.getList();
        })
      }).catch(() => {
        this.$message({  message: '操作失败', type: 'error' })
      });
    },
    //初始化表单数据，重新渲染
    initDataForm(){
      this.dataForm = {
        useLimit: '' ,
        userLimit: '' ,
        couponNum: '' ,
        activeSecret: '' ,
        effectiveDay: '' ,
        id: '' ,
        discountRatio: '' ,
        couponName: '' ,
        type: '' ,
        grantNum:'',
        activeCode: '' ,
        limitCount:'',
        isShow:0,
      };
    },
    //关闭表单弹出框
    closeDialog(){
      this.$refs['dataForm'].resetFields();
      this.dialogFormVisible = false
    },

    heandleUserOptions(){
      this.$api.getUserList().then(
          res=>{
            this.userOptions = res.data
          }
      )
    },

    heandleQuestionOptions(){
      this.$api.getCourseList().then(
          res=>{
            this. questionOptions= res.data
          }
      )
    },

    heandleExamOptions(){
      this.$api.getExamList().then(
          res=>{
            this.examOptions= res.data
          }
      )
    },
    handleInfo(row){
      this.pid = row.id
      this.itemDialog = true
    },




  }


}
</script>
